# coding:utf8
"""
python中的数据结构与算法
"""

# 1.解压序列给多个变量
data = ["ACME", 50, 91.1, (2019, 11, 24)]
name, _, decimals, (year, _, day) = data
print(name, decimals, year, day)
s = 'Hello'
a, b, c, d, e = s
print(a, b, c, d, e)

# 2.解压可迭代对象赋值给多个变量
*trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
print(trailing, current)
records = [
    ('foo', 1, 2),
    ('bar', 'hello'),
    ('foo', 3, 4),
]


def do_foo(x, y):
    print('foo', x, y)


def do_bar(s):
    print('bar', s)


for tag, *args in records:
    if tag == 'foo':
        do_foo(*args)
    elif tag == 'bar':
        do_bar(*args)

line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'
uname, *fields, homedir, sh = line.split(':')
print(line.split(':'))
print(uname, fields, homedir, sh)

record = ('ACME', 50, 123.45, (12, 18, 2012))
name, *_, (*_, year) = record
print(name, year)
items = [1, 3, 5, 8, 9]
a, *b = items
print(a, b)


def sum(items):
    head, *tail = items
    return head + sum(tail) if tail else head


print(sum(items))

print("--3.保留最后N个元素--")
from collections import deque


def search(lines, pattern, history=5):
    base_line = deque(maxlen=history)
    print('base_line', base_line)
    for line in lines:
        if pattern in line:
            yield line, base_line
        base_line.append(line)


with open('C:/Program Files/AnChnet/workspace/DJangoSpace/demo/tests/test_rabbitmq_receive.py', mode='r') as fr:
    for line, base in search(fr, 'smart', 5):
        for pline in base:
            print('pline', pline, end='')
        print('line', line, end='')
        print('-' * 20)

print("--4.查找最大或最小的N个元素--")
import heapq

num = [1, 3, -4, 3.3, 6, 75, 97, 12, -6]
print(heapq.nlargest(3, num))
print(heapq.nsmallest(3, num))
portfolio = [
    {'name': 'IBM', 'shares': 100, 'price': 91.1},
    {'name': 'AAPL', 'shares': 50, 'price': 543.22},
    {'name': 'FB', 'shares': 200, 'price': 21.09},
    {'name': 'HPQ', 'shares': 35, 'price': 31.75},
    {'name': 'YHOO', 'shares': 45, 'price': 16.35},
    {'name': 'ACME', 'shares': 75, 'price': 115.65}
]
print(heapq.nlargest(3, portfolio, key=lambda k: k['price']))
print(heapq.nsmallest(3, portfolio, key=lambda k: k['price']))

print("实现一个优先级队列")


class PriorityQueue:
    def __init__(self):
        self._queue = []
        self._index = 0

    def push(self, item, priority):
        # heapq.heappush(self._queue, (-priority, self.index, item))
        heapq.heappush(self._queue, (-priority, self._index, item))
        self._index += 1

    def pop(self):
        return heapq.heappop(self._queue)[-1]


class Item:
    def __init__(self):
        self.name = name

    def __repr__(self):
        return 'Item({!r})'.format(self.name)


q = PriorityQueue()
q.push(Item('foo'), 1)
q.push(Item('foo1'), 2)
q.push(Item('foo2'), 5)
print(q.pop())
